package com.xu.wemall.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xu.wemall.commons.enums.ResultEnum;
import com.xu.wemall.commons.exceptions.BizException;
import com.xu.wemall.commons.utils.JwtUtils;
import com.xu.wemall.commons.components.UserExcelListener;
import com.xu.wemall.entry.Goods;
import com.xu.wemall.entry.User;
import com.xu.wemall.service.IGoodsService;
import com.xu.wemall.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p >
 *
 * @author astupidcoder
 * @since 2020-05-13
 */
@Slf4j
@Api(tags = "User操作接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IGoodsService iGoodsService;

    @Autowired
    private IUserService iUserService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Map<String, Object> userLogin(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(User::getUserName, user.getUserName())
                .eq(User::getPassword, user.getPassword());
        User record = iUserService.getOne(queryWrapper);
        Map<String, Object> resultMap = new HashMap<>();
        if (record != null) {
            String token = JwtUtils.generateToken(String.valueOf(user.getId()),
                    user.getUserName(), user.getPassword());
            resultMap.put("user", record);
            resultMap.put("Authorization", "Bear " + token);
        }
        return resultMap;
    }

    @ApiOperation("条件查询")
    @GetMapping("/getByCondition")
    public List<User> getByCondition(String username, String password) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(User::getUserName, username)
                .eq(User::getPassword, password);
        List<User> userList = iUserService.list(queryWrapper);
        if (userList.isEmpty()) {
            throw new BizException(ResultEnum.BIZ_EXCEPTION);
        }
        return userList;
    }

    @ApiOperation("根据ID添加")
    @GetMapping("/getById")
    public User getUser(Integer id) {
        User user = iUserService.getById(id);
        if (user == null) {
            throw new BizException(ResultEnum.BIZ_EXCEPTION);
        }
        return user;
    }

    @ApiOperation("分页查询")
    @GetMapping("/getPageList")
    public IPage<User> getPageList() {
        Page<User> iPage = new Page<>(1, 10);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        IPage<User> userRecord = iUserService.page(iPage, queryWrapper);
        userRecord.getRecords().forEach(System.out::println);
        return userRecord;
    }

    @ApiOperation("添加")
    @PostMapping("/register")
    public Boolean inserUser(@RequestBody User user) {
        // count是新增的条数
        return iUserService.save(user);
    }

    @ApiOperation("更新")
    @PutMapping("/update")
    public Boolean updateUser(@RequestBody User user) {
        // count是更新的条数
        Boolean count = iUserService.updateById(user);
        // 故意造成一个空指针异常，并且不进行处理
        String str = null;
        str.equals("111");
        return count;
    }

    @ApiOperation("删除")
    @DeleteMapping("/delete")
    public Integer deleteUser(@RequestBody User user) {
        // count是更新的条数
        // 这里故意造成一个异常，并且不捕获处理
        Integer.parseInt("xulijun137");
        return 0;
    }

    @Autowired
    private UserExcelListener userExcelListener;

    @ApiOperation("导入")
    @GetMapping("/import")
    public String importExcel(String filePath) {

        // 这里需要注意 UserExcelListener的doAfterAllAnalysed 会在每个sheet读取完毕后调用一次。然后所有sheet都会往同一个UserExcelListener里面写
        EasyExcel.read(filePath, User.class, userExcelListener).doReadAll();

        //ExcelReader excelReader = EasyExcel.read(filePath).build();
        // 这里为了简单 所以注册了 同样的head 和Listener 自己使用功能必须不同的Listener
//        ReadSheet readSheet1 = EasyExcel.readSheet(0).head(User.class).registerReadListener(userExcelListener).build();
//        ReadSheet readSheet2 = EasyExcel.readSheet(1).head(User.class).registerReadListener(userExcelListener).build();
        // 这里注意 一定要把sheet1 sheet2 一起传进去，不然有个问题就是03版的excel 会读取多次，浪费性能
//        excelReader.read(readSheet1, readSheet2);
        // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
        //excelReader.finish();
        return "SUCESS";

    }

    @ApiOperation("导出")
    @GetMapping("/export")
    public String download(HttpServletResponse response) throws IOException {

        String fileName = "export_" + System.currentTimeMillis() + ".xlsx";

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        // 这里 需要指定写用哪个class去写
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), User.class).build();
        // 这里注意 如果同一个sheet只要创建一次
        WriteSheet writeSheet = EasyExcel.writerSheet("Sheet_1").build();

        List<User> data = iUserService.list();
        //写数据
        excelWriter.write(data, writeSheet);
        excelWriter.finish();
        return "SUCESS";
    }

}
